package com.gzf.messagedigest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {

    private String str = "陈1白2帆3这4个5大6傻7逼";
    private EditText input, output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        input = (EditText) findViewById(R.id.input);
        output = (EditText) findViewById(R.id.output);
    }

    public void mdMessage(View view) {
        String data = input.getText().toString();
        switch (view.getId()) {
            case R.id.md5:
                if (data.length() > 0 && !data.equals("")) {
                    str = data;
                }
                String md5 = messageDigest("MD5", str);
                output.setText(md5);
                break;
            case R.id.sha1:
                if (data.length() > 0 && !data.equals("")) {
                    str = data;
                }
                String sha1 = messageDigest("SHA1", str);
                output.setText(sha1);
                break;
        }
    }

    private String messageDigest(String type, String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(type);
            messageDigest.update(data.getBytes());
            byte[] digest = messageDigest.digest();
            int length = digest.length;
            Log.d("TAG", "---------------------->: " + length);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < length; i++) {
                int b = digest[i] & 0xff;
                if (b<0xf){
                    builder.append(0);
                }
                String hex = Integer.toHexString(b);
                builder.append(hex);
            }
            return builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
